<!-- 商品详细页 -->
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert
        show-icon
        :closable="false"
        title="注意:只允许为第三级分类设置相关参数!"
        type="warning"
      />

      <el-row>
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader
            v-model="selectCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            @click="addDialogVisible = true"
            :disabled="isBtnDisabled"
            >添加参数</el-button
          >
          <el-table :data="manyTabData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                >
                  {{ item }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>

            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>

            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  @click="editDialogShow(scope.row.attr_id)"
                  icon="el-icon-edit"
                  size="mini"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  @click="removeParams(scope.row.attr_id)"
                  icon="el-icon-delete"
                  size="mini"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态页面面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >

          <!-- 静态属性表格展示 -->
          <el-table :data="onlyTabData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand"></el-table-column>
            <el-table-column type="index" label="#"></el-table-column>

            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>

            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  @click="editDialogShow(scope.row.attr_id)"
                  icon="el-icon-edit"
                  size="mini"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  @click="removeParams(scope.row.attr_id)"
                  icon="el-icon-delete"
                  size="mini"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加静态/动态属性对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <el-form
        :model="addForm"
        :rules="addrules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑静态/动态属性对话框 -->
    <el-dialog
      :title="'编辑' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <el-form
        :model="editForm"
        :rules="editRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      // 商品分类信息列表
      cateList: [],
      // 级联选择框的配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 选择框选择的值
      selectCateKeys: '',
      // 当前活跃的Tabs标签页
      activeName: 'only',
      // 动态参数和静态参数
      manyTabData: [],
      onlyTabData: [],
      // 添加属性对话框
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addrules: {
        attr_name: [
          {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }
        ]
      },
      editDialogVisible: false,
      editForm: {},
      editRules: {
        attr_name: [
          {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取分类参数列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status != 200)
        return this.$message.error('获取商品分类数据失败')
      this.cateList = res.data
    },
    // 级联选择器选中后 触发的函数
    handleChange() {
      this.getParamsData()
    },
    // 点击tab栏触发的函数
    handleTabClick() {
      if (!this.cateId) return
      this.getParamsData()
    },
    // 获取商品参数的数据
    async getParamsData() {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg)
      }
      // 将每个参数的attr_vals都遍历出来并重新赋值新数组
      res.data.forEach(element => {
        element.attr_vals = element.attr_vals
          ? element.attr_vals.split(',')
          : []
      })
      // 分别储存静态或动态数据
      if (this.activeName == 'many') {
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },

    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加属性/参数
    addParams() {
      this.$refs.addFormRef.validate(async vali => {
        if (!vali) return

        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status != 201) {
          return this.$message.error(res.meta.msg)
        }
        this.getParamsData()
        this.addDialogVisible = false
        this.$message.success(res.meta.msg)
      })
    },
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑对话框显示时候的回调
    async editDialogShow(attrId) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attrId}`
      )
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 编辑参数对话框确认时的回调
    editParams() {
      this.$refs.editFormRef.validate(async vali => {
        if (!vali) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status != 200) {
          return this.$message.error(res.meta.msg)
        }
        this.getParamsData()
        this.$message.success(res.meta.msg)
        this.editDialogVisible = false
      })
    },

    async removeParams(attId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult != 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 确认删除的业务逻辑
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attId}`
      )
      if (res.meta.status != 200) {
        return this.$message.error('删除请求失败')
      }
      this.getParamsData()
      this.$message.success('删除成功')
    }
  },

  computed: {
    // 当选中三级菜单的时候返回false
    isBtnDisabled() {
      return this.selectCateKeys.length != 3
    },
    cateId() {
      // 返回选中三级菜单的所属分类id值
      return this.isBtnDisabled ? null : this.selectCateKeys[2]
    },
    // 获取活跃页面的名称
    titleText() {
      return this.activeName == 'many' ? '动态参数' : '静态属性'
    }
  }
}
</script>
<style lang="less" scoped>
.el-alert {
  margin-bottom: 15px;
}
.el-cascader {
  margin-left: 15px;
}
.el-tag {
  margin-right: 10px;
}
</style>
